<template>
	<view>
		<!-- 自定义头部组件 -->
		<HeaderTitle title="添加行程与客户拜访" :isBack="true" :isSearch="false" />
		<!--添加行程明细 -->
		<view style="background-color: #fff;margin-top: 20rpx;">

			<view>
				<uni-section title="基本信息" type="line"></uni-section>
			</view>
			<view style="height: 100%;padding-top: 20rpx;">

				<uni-forms ref="form" :modelValue="entity" label-width="130px">
					<!-- 行程名称 -->
					<view style="background-color: #fff;padding:0 20rpx;">
						<uni-forms-item label="行程名称:" name="ItineraryName">
							<uni-easyinput v-model="entity.ItineraryName" :inputBorder="false" />
						</uni-forms-item>
					</view>
					<!-- 选择客户 -->
					<view style="background-color: #fff;padding:0 20rpx;">
						<uni-forms-item label="客户:" name="CustomerName">
							<view @click="CustomerChoice">
								<uni-easyinput v-model="entity.CustomerName" suffixIcon="compose" :inputBorder="false"
									disabled />
							</view>
						</uni-forms-item>
					</view>

					<!-- 到达城市 -->
					<view style="background-color: #fff;padding:0 20rpx;">
						<uni-forms-item label="到达城市:" :rules="$rules.handle.ArrivalCityIdName" required
							name="ArrivalCityIdName">
							<uni-data-picker popup-title="请选择到达城市" :localdata="dataTree"
								@change="pickerChange($event, 'ArrivalCityIdName')" :inputBorder="false"
								v-model="entity.ArrivalCityIdName">
							</uni-data-picker>
						</uni-forms-item>
					</view>
					<!-- 都打日期 -->
					<view style="background-color: #fff;padding:0 20rpx;">
						<uni-forms-item label="到达日期:" :rules="$rules.handle.ArrivalDate" required name="ArrivalDate">
							<view @click="DateChange($event, 'ArrivalDate')">
								<uni-easyinput v-model="entity.ArrivalDate" :disabled="true" :inputBorder="false" />
							</view>
						</uni-forms-item>
					</view>
					<!-- 交通方式 -->
					<view style="background-color: #fff;padding:0 20rpx;">
						<uni-forms-item label="交通方式:" name="TransportationMode"
							:rules="$rules.handle.TransportationMode" required>
							<view>
								<uni-data-select :clear="false" style="background-color: #fff;border-radius: 10rpx;"
									v-model="entity.TransportationMode" :localdata="ModeTransportationOptions"
									@change="selectOptionsChange($event, 'ModeTransportation')"
									:disabled="disabled"></uni-data-select>
							</view>
						</uni-forms-item>
					</view>
					<!-- 客户拜访说明 -->
					<view style="background-color: #fff;padding:0 20rpx;">
						<!-- :rules="$rules.handle.VisitRemark" required  -->
						<uni-forms-item label="客户拜访说明:" name="Infor">
							<view>
								<uni-easyinput v-model="entity.Infor" type="textarea" :adjust-position="false"
									:inputBorder="false" />
							</view>
						</uni-forms-item>
					</view>

				</uni-forms>
				<!-- 关联沟通记录和添加沟通记录 -->
				<view v-if="entity.CustomId" class="flex Acentern"
					style="padding-right: 25rpx;padding-left: 20rpx;margin-bottom: 30rpx;margin-top: 15rpx;">
					<view class="flex Acentern" style="margin-right: 50rpx;" @click="CommunicationClick(1)">
						<u-icon name="plus-circle-fill" color="#2979ff" size="45"></u-icon>
						<text style="color:#2979ff;font-weight:bold;padding-left: 10rpx;">关联沟通记录</text>
					</view>
					<view class="flex Acentern" @click="CommunicationClick(2)">
						<u-icon name="plus-circle-fill" color="#2979ff" size="45"></u-icon>
						<text style="color:#2979ff;font-weight:bold;padding-left: 10rpx;">添加沟通记录</text>
					</view>
				</view>
				<!-- 关联的沟通记录列表 -->
				<view v-if="entity.salesmanDailyRecords" style="">
					<view v-if="entity.salesmanDailyRecords.length>0">
						<view style="font-size: 25rpx;padding-left: 20rpx;font-weight: bold;">已关联的沟通记录:</view>
						<block v-for="(item, index) in entity.salesmanDailyRecords" :key="index">
							<view style="display: flex;flex-wrap: wrap;padding-left: 20rpx;padding-right: 20rpx;">
								<u-tag @close="tagCloseChange(item, index)" @click="tagClickChange(item, index)"
									style="margin-right: 20rpx;margin-bottom: 15rpx;" :text="item.DailyRecordTitle"
									type="primary" closeable />
							</view>

						</block>
					</view>
				</view>
			</view>
			<view class="flex  Jbetween" style="">
				<uni-section title="费用明细" type="line"></uni-section>
				<view class="flex Acenter Jbetween" @click="AddDetailClick" style="padding-right: 25rpx;">
					<u-icon name="plus-circle-fill" color="#2979ff" size="45"></u-icon>
					<text style="color:#2979ff;font-weight:bold;padding-left: 10rpx;">添加明细</text>
				</view>
			</view>

			<view class="scrollBox" style="">
				<scroll-view style="width: 100%;height: 100%;" scroll-y="true">
					<view style="padding-bottom: 50px;">
						<!-- 报销费用明细 -->
						<view class="detail" v-for="(item, index) in detailData" :key="index">
							<view class="bold " style="font-size: 14px; color: #000;margin-bottom: 10rpx;">
								客户:<span class="font">{{item.CustomerName}}</span>
							</view>
							<view class="flex Jbetween" style="font-size: 14px">
								<span class="font">票据日期: {{ item.BillDate || "无" }}</span>
								<span class="font">业务性质:
									{{ item.ExpenseType || "无" }}</span>
							</view>
							<view class="flex Jbetween" style="font-size: 14px">
								<span class="font">票据类型: {{ item.BillTypeName || "无" }}</span>
								<span class="font">发票分类: {{ item.InvoiceClassificationName || "无" }}</span>
							</view>
							<view class="flex Jbetween" style="font-size: 14px">
								<span class="font">票据张数: {{ (item.BillsNum ?item.BillsNum : 0) +' 张' || "无" }}</span>
								<span class="font">是否无票支出: {{ item.IsBill == true ? '是' : "否" }}</span>
							</view>
							<view class="flex Jbetween" style="font-size: 14px">
								<span class="font">票面金额: {{ item.FaceAmount || "无" }}</span>
								<span class="font">报销金额: {{ item.ReimburseAmount || "无" }}</span>
							</view>
							<view class="flex Jbetween" style="font-size: 14px">
								<span class="font">摘要:{{item.ItemAbstract}}</span>
							</view>
							<view v-if="item.reimburse_Files" class="flex Jbetween" style="font-size: 14px">
								<span v-if="item.reimburse_Files.length>0" class="font">附件 *
									{{item.reimburse_Files.length}}</span>
								<span v-else class="font">附件 *0</span>
							</view>
							<view v-else class="flex Jbetween" style="font-size: 14px">
								<span class="font">附件 *0</span>
							</view>
							<view class="flex Jend">
								<view @click.stop="handleItemEdit(entity, item, index)" style="
								  width: 15%;
								  border-radius: 5px;
								  line-height: 30px;
								  color: #fff;
								  text-align: center;
								  margin-top: 10rpx;
								  background-color: #2979ff;
								  margin-right: 30rpx;
								">
									修改
								</view>
								<view @click="detailDataDelete([item.Id], index)" style="
								  width: 15%;
								  border-radius: 5px;
								  line-height: 30px;
								  color: #fff;
								  text-align: center;
								  margin-top: 10rpx;
								 background-color: red;
								">
									删除
								</view>
							</view>
						</view>
						<view style="margin: 50rpx 0;">
							<u-empty v-if="detailData.length==0" text="请添加费用明细" mode="list"></u-empty>
						</view>
					</view>

				</scroll-view>
			</view>
			<view v-if="detailData.length > 0" class="submitButton">
				<u-button type="primary" @click="handleSubmitDetailSave">保存</u-button>
			</view>

			<!-- 引用客户组件 -->
			<Myuser @customerChoice="Client" ref="myuser" />

			<!-- 引用沟通关联组件 -->
			<CommunicationVue ref="CommunicationVue" @CommunicationConfirm="CommunicationConfirm" />
			<!-- 选择日期 -->
			<u-calendar v-model="isCalendar" :mode="mode" placeholder="请选择日期" @change="calendarChange"></u-calendar>
		</view>

	</view>

</template>

<script>
	// 沟通关联组件
	import CommunicationVue from "../../components/Communication.vue";
	//客户
	import Myuser from "../../components/Myuser.vue";
	// 引入顶部navbar组件
	import HeaderTitle from '@/components/header/header-title.vue'
	import {
		mapState
	} from "vuex";
	export default {
		components: {
			// 客户组件
			Myuser,
			// 沟通关联组件
			CommunicationVue,
			// 引入头部组件
			HeaderTitle
		},
		data() {
			return {
				entity: {},
				// 是否显示日期弹窗
				isCalendar: false,
				// 日期选择
				mode: 'date',
				// 禁用
				disabled: false,
				// 加载
				loading: false,
				// 点击的是开始日期还是结束日期
				DateType: "",
				// 地区树结构
				dataTree: [],
				// 费用明细列表
				detailData: [],
				// 交通方式下拉列表数据
				ModeTransportationOptions: [],
				// 传递过来的主表entity
				options: {}

			}
		},
		computed: {
			...mapState(["UserInfo", "BillTypeOptions", "ExpenseTypeOptions", "InvoiceClassificationOptions",
				"CompayListOptions", "Base_DistrictGetTreeDataOptions", "TransportationModeOptions",
				"CustomerInfoOptions"
			]),
		},
		onLoad(options) {
			this.options = options
			// 城市的确树结构
			this.dataTree = this.Base_DistrictGetTreeDataOptions
			// 交通方式下拉列表数据
			this.ModeTransportationOptions = this.TransportationModeOptions
		},
		methods: {
			// 添加和关联沟通记录点击
			CommunicationClick(type) {
				console.log('添加还是关联', type, this.entity)
				if (type == 1) {
					// 点击的是关联沟通记录
					// 选择关联沟通记录列表
					this.$refs.CommunicationVue.openForm(this.entity.CustomerNameOptions, this.entity.salesmanDailyRecords)

				} else {
					// 点击的是添加沟通记录
					uni.navigateTo({
						url: "/pages/Cust_Communication/AddForm?title=新建沟通记录&CustomId=" + this.entity.CustomId +
							'&CustomerName=' + this.entity.CustomerName
					})
				}
			},
			// 已关联沟通记录查看详情
			tagClickChange(item, index) {
				uni.navigateTo({
					url: "/pages/Cust_Communication/EditForm?Id=" + item.Id + "&title=查看沟通记录"
				})
			},
			// 已关联的沟通记录列表删除
			tagCloseChange(item, index) {
				this.entity.salesmanDailyRecords.splice(index, 1)
				this.$forceUpdate()
			},
			// 添加明细
			AddDetailClick() {
				let entity = JSON.stringify(this.entity)
				uni.setStorageSync('entity', entity)
				// 报销明细
				uni.navigateTo({
					url: "/pages/Approval/AddDetailReim"
				})
			},
			// 交通方式选择
			selectOptionsChange(event, key) {
				console.log('交通方式选择', event, key, this.entity, this.ModeTransportationOptions)
				// 处理交通方式名称用于渲染
				let ModeTransportationOptionsName = this.ModeTransportationOptions.filter(item => item.value == event)[0]
					.text
				this.$set(this.entity, key + 'Name', ModeTransportationOptionsName)
				this.$set(this.entity, 'ModeTransportationOptions', this.ModeTransportationOptions[event])
			},
			//选择客户
			CustomerChoice() {
				this.$refs.myuser.openForm();
			},
			//本条客户的数据
			Client(arr) {
				console.log('选择客户确定好后传递父组件的值---------------', arr, this.entity)

				let CustomerNameArr = arr.map(item => {
					return item.cCusName
				})
				let CustomIdArr = arr.map(item => {
					return item.Id
				})
				let CustomerName = CustomerNameArr.join(',')
				let CustomId = CustomIdArr.join(',')

				this.$set(this.entity, "CustomerName", CustomerName);
				this.$set(this.entity, "CustomName", CustomerName);
				this.entity.CustomId = CustomId
				// 直接插入选中的下拉客户数组  用于添加行程明细选择客户使用
				this.$set(this.entity, "CustomerNameOptions", arr);
				// 选择关联沟通记录列表
				this.$refs.CommunicationVue.openForm(arr)

			},

			// 关联沟通记录子组件回调
			CommunicationConfirm(data) {
				// 过滤出选中的列表
				let arr = data.filter(item => item.checked == true)
				console.log('关联沟通记录子组件回调--', data, this.entity, arr)
				if (arr.length == 0) {
					// 判断返回的关联沟通记录结果过来的是否是空数组  默认格式化数据
					// 如果没有关联沟通记录  默认空数组
					if (data.length == 0) {
						// 插入参数传给后台记录
						this.entity['salesmanDailyRecords'] = this.entity.salesmanDailyRecords ? this.entity
							.salesmanDailyRecords : []
						return
					}
					// 说明灭有选择关联的沟通记录列表
					return
				}
				if (!this.entity.salesmanDailyRecords) {
					// 插入参数传给后台记录
					this.entity['salesmanDailyRecords'] = arr
				} else {
					this.entity.salesmanDailyRecords = this.entity.salesmanDailyRecords.concat(arr)
				}

				console.log('EditDetailTrip关联子组件回调回来的data', data, arr, this.entity)
				// 如果没有关联沟通记录  默认空数组
				// if (data.length == 0) {
				// 	// 插入参数传给后台记录
				// 	this.entity['salesmanDailyRecords'] = []
				// 	return
				// }
				// // 过滤出选中的列表
				// let arr = data.filter(item => item.checked == true)
				// // 插入参数传给后台记录
				// this.entity['salesmanDailyRecords'] = arr
				console.log('关联子组件回调回来的data', data, arr, this.entity)
				this.$forceUpdate()
			},
			//到达城市选择
			pickerChange(event, key) {
				let arr = event.detail.value
				// 出发城市名称
				let ArrivalCityIdName = arr.map(item => {
					return item.text
				}).join('/')
				// 出发城市id
				let ArrivalCityId = arr.map(item => {
					return item.value
				}).join('/')
				this.$set(this.entity, 'newArrivalCityId', ArrivalCityId)
				this.$set(this.entity, 'newArrivalCityIdName', ArrivalCityIdName)
				this.$set(this.entity, 'ArrivalCityIdName', event.detail.value)
				console.log('到达城市选择了', event, this.entity, this.Base_DistrictGetTreeDataOptions)
			},
			// 选择日期确定
			calendarChange(event) {
				if (this.options.DepartureDate === 'undefined') {
					this.$errorToast('您没有选择出发日期')
					return
				}
				let DepartureDate = new Date(this.options.DepartureDate).getTime()
				// 当前选择的到达日期
				let ArrivalDate = new Date(event.result).getTime()
				if (ArrivalDate < DepartureDate) {
					this.$errorToast('到达日期不能小于出发日期')
					return
				}
				if (this.options.ReturnDate === 'undefined') {
					this.$errorToast('您没有选择返回日期')
					return
				}
				let ReturnDate = new Date(this.options.ReturnDate).getTime()
				if (ArrivalDate > ReturnDate) {
					this.$errorToast('到达日期不能大于返回日期')
					return
				}
				// *************注意  存储必须用set赋值  否则校验不通过   ************************************
				this.$set(this.entity, 'ArrivalDate', event.result);
				// *************注意  存储必须用set赋值  否则校验不通过   ************************************
			},
			// 出发日期和到达日期选择
			DateChange(event, key) {
				this.isCalendar = true
			},
			// 费用明细子表删除
			detailDataDelete(type, event, index) {
				console.log('行程子表开始删除了------------', type, event, index)
				this.detailData.splice(index, 1)
			},
			// 子表编辑
			handleItemEdit(entity, item, index) {
				this.detailDataIndex = index
				if (item.CustomId) {
					let CustomerNameOptions = []
					// 单独处理客户的下拉列表数据
					let CustomIdArr = item.CustomId.split(',')
					let CustomerNameArr = item.CustomerName.split(',')
					this.CustomerInfoOptions.forEach(v => {
						CustomIdArr.forEach(m => {
							if (v.Id === m) {
								CustomerNameOptions.push(v)
							}
						})
					})
					item.CustomerNameOptions = CustomerNameOptions
					console.log('行程费用明细修改了', item, index, CustomIdArr, CustomerNameArr)
				}
				let data = {
					entity: entity,
					item: item
				}
				uni.setStorageSync('entity', data)
				uni.navigateTo({
					url: "/pages/Approval/EditDetailReim"
				})

			},
			// push报销明细子表
			setDetailData(type, data) {
				if (type === 'add') {
					// 走新增逻辑
					console.log('这里是新增费用明细了---------', type, data)
					this.detailData.push(data)
				} else {
					// 走修改逻辑
					console.log('这里是编辑费用明细了---------', type, data)
					let newDetailData = this.detailData
					newDetailData.forEach((item, index) => {
						if (item.Id && item.Id === data.Id) {
							newDetailData[index] = data
						} else {
							// 替换数组里对应对象
							this.detailData.splice(this.detailDataIndex, 1, data)
						}
					})
				}

			},
			// 添加行程保存
			handleSubmitDetailSave() {
				var that = this
				this.$refs.form.validate().then(res => {
					let pages = getCurrentPages() // 获取当前页面栈的实例，以数组形式按栈的顺序给出，第一个元素为首页，最后一个元素为当前页面。
					let prevPage = pages[pages.length - 2] //上一页页面实例

					this.entity['detailData'] = this.detailData
					this.detailData.forEach(item => {
						if (!item.reimburse_Files) {
							item.reimburse_Files = []
						}
						// 单独处理票据张数 如果没有填写默认0 否则最终保存回报错
						item.BillsNum = item.BillsNum ? item.BillsNum : 0
						// 处理业务性质参数传递
						item.ExpenseType = item.newExpenseType //名称
						item.ExpenseTypeId = item.newExpenseTypeId //id
					})
					console.log('差旅报销添加行程行程行程可以保存了----------------------------', this.entity, this.detailData)
					uni.navigateBack({
						delta: 1,
						success: () => {
							prevPage.$vm.setDetailData('add', '行程', this
								.entity) // 给上一页绑定方法otherFun,传参地址id
						}
					})

				}).catch(err => {})
			},
			init() {},
			openForm(data) {
				this.init()
			},
			close() {
				this.$emit('close')
			}
		}
	}
</script>

<style lang="less" scoped>
	/* 设置 label 的样式 */
	::v-deep.uni-forms-item {
		padding-right: 40rpx !important;

		/* 例如，设置 label 的宽度和对齐方式 */
		.uni-forms-item__label {
			display: flex !important;
			justify-content: flex-end !important;
		}
	}

	// 覆盖uniapp 的 uni-data-select 央视
	::v-deep.uni-select {
		border: none !important;
	}

	// 覆盖uni-data-pirker 样式
	::v-deep.input-value-border {
		border: none !important;
	}

	// 覆盖uviewform表单form-item的下边距
	::v-deep.uni-forms-item {
		margin-bottom: 0 !important;
		border-bottom: 1px solid #EEE;
		padding-top: 20rpx !important;
		padding-bottom: 20rpx !important;
	}

	.scrollBox {

		margin-bottom: 130rpx;
		/* #ifdef H5 */
		height: calc(100vh - 360px);
		/* #endif */
		/* #ifdef APP */
		height: calc(100vh - 220px);
		/* #endif */

		.detail {
			width: 100%;
			margin: 0 auto;
			box-shadow: 3px 4px 16px 0px #6b6b6a;
			margin-top: 40rpx;
			margin-bottom: 10px;
			background-color: #ffffff;
			border-radius: 10rpx;
			padding: 20rpx;
		}
	}

	.submitButton {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		height: 100rpx;
		/*暂时发现安卓小屏手机安全区为0 && 不带单位的话padding-bottom会失效，写一个兜底, 并写在最上面；f12发现css样式如果都给height设置样式，会依次往下，用最底下的一个样式，如果最下面的没失效，依次往上查找，所以兜底的写在最上面 */
		height: calc(130rpx + constant(safe-area-inset-bottom));
		/* 直接扩展高度，因为padding-bottom是内边距 */
		height: calc(130rpx + env(safe-area-inset-bottom));
		/* 直接扩展高度 */
		background: #fff;
		padding-top: 10rpx;
		box-sizing: border-box;
		padding-bottom: constant(safe-area-inset-bottom);
		/*兼容 iOS<11.2 */
		padding-bottom: env(safe-area-inset-bottom);
		/* 兼容iOS>= 11.2*/
		border-top: 1px solid #e9e9e9;
		padding-left: 15px;
		padding-right: 15px;
	}
</style>